<template>
	<view class="account-container">
        <u-navbar title="账户余额" :custom-back="handleClose">
            <view slot="right" class="u-p-l-20 u-p-r-20" style="color: #666666;" @click="handleDetailed">
                明细
            </view>
        </u-navbar>
        <view class="account-balance-box">
            <view class="account-balance">¥ {{account_balance | unitPrice}}</view>
            <view class="account-balance-tip">仅限用于本商城购买商品使用，不能提现</view>
        </view>
        <view class="account-from">
            <view class="account-recharge">
                <view class="account-recharge-title">充余额</view>
                <view class="account-recharge-box">
                    <view class="account-recharge-lable">金额：</view>
                    <view class="input-group">
                        <input v-model="rechargeNumber" type="number" placeholder="请输入充值金额" class="input-inner">
                        <view class="input-append">元</view>
                    </view>
                </view>
            </view>
        </view>
        <view class="payment-view u-margin-top-30">
            <view class="u-flex u-row-between u-p-25" :class="index > 0 ? 'cell-view' : '' " @click="handlePaymentType(pay.plugin_id)" v-for="(pay, index) in paymentList" :key="index">
                <view class="cell-icon">
                    <u-image width="200" height="60" :src="pay.image"></u-image>
                </view>
                <view class="cell-title">
                    {{ pay.method_name }}
                </view>
                <view class="cell-right-icon">
                    <u-icon :name="pay.selected ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                </view>
            </view>
        </view>
        <view class="big-btn" @click="initiatePay">
            <view class="btn u-flex u-row-center">立即支付</view>
        </view>
        <!-- #ifdef H5 -->
         <div class="__pay_form__"></div>
        <!-- #endif -->
	</view>
</template>

<script>
    import * as API_Deposit from '@/api/deposit'
    import * as API_Trade from '@/api/trade.js'
    import * as Payment from '@/common/payment.js'
    import * as API_Openid from '@/api/openid.js'
    import Cache,{Keys} from '@/utils/cache.js'
    import { Foundation, RegExp } from '@/ui-utils/index.js'
	export default {
		data() {
			return {
                showPayMentWay: false,
                // 预存款余额
                account_balance: '',
                // 充值金额
                rechargeNumber: '',
                // 是否是微信浏览器
                isWechatBroswer: false,
                payment_plugin_id: '' ,//支付方式
                paymentList: [], //支付方式列表
                openid: ''
			};
		},
        onLoad(options) {
            this.getDepositBalance()
            this.getPaymentList()
            this.openid= Cache.getItem(Keys.wxopenid)

            if(options.is_callback == 'yes'){
                this.payCallback()
            }

            // #ifdef APP-PLUS
            this.openid = 'appopenid'
            // #endif

            // #ifdef H5
            let code = options.code || ''
            this.loadH5OpenId(code)
            // #endif

            // #ifdef MP-WEIXIN
            this.loadMiniOpenId()
            // #endif
        },
        methods: {
            //是否是微信浏览器
            is_weixin(){
                let ua = navigator.userAgent.toLowerCase();
                if(ua.match(/MicroMessenger/i) == "micromessenger") {
                    return true;
                } else {
                    return false;
                }
            },
            //明细列表
            handleDetailed() {
                uni.navigateTo({
                    url:"/mine-module/balance-detailed"
                })
            },
            //选择支付方式
            handlePaymentType(plugin_id) {
                this.paymentList.forEach(item => {
                    item.selected = false
                    if(item.plugin_id === plugin_id) {
                        item.selected = true
                    }
                })
                this.payment_plugin_id = plugin_id
            },
            //支付
            async initiatePay() {
                if(!this.rechargeNumber) {
                    this.$u.toast('充值金额不能为空')
                    return
                } else if (!RegExp.money.test(this.rechargeNumber)) {
                    this.$u.toast('请输入正整数或者两位小数')
                    return
                } else if (parseInt(this.rechargeNumber) < 1) {
                    this.$u.toast('充值金额最少1元')
                    return
                } else if (!this.payment_plugin_id) {
                    this.$u.toast('请选择支付方式')
                    return
                } else if(this.openid == 'error'){
                    this.$u.toast(`openid不正确，不能支付`)
                    return
                }

                // #ifdef APP-PLUS
                const client_type = 'NATIVE'
                // #endif

                // #ifdef H5
                const client_type = 'WAP'
                // #endif

                // #ifdef MP-WEIXIN
                const client_type = 'MINI'
                // #endif

                API_Deposit.createRechargeOrder(this.rechargeNumber).then(response => {
                    const params = {
                        payment_plugin_id: this.payment_plugin_id,
                        pay_mode: 'normal',
                        client_type: client_type,
                        openid: this.openid
                    }
                    API_Deposit.paymentRechargeOrder(params, response.recharge_sn).then(result => {
                        if (params.payment_plugin_id === 'weixinPayPlugin') {
                            //微信内嵌H5，调用wechatH5Pay方法
                            // #ifdef H5
                            if (typeof WeixinJSBridge == "undefined"){
                                Payment.mobileH5Pay(result,this.payCallback,this.payFail)
                            }else{
                                Payment.wechatH5Pay(result,this.payCallback,this.payFail)
                            }
                            // #endif

                            //微信小程序，调用wechatMiniPay方法
                            // #ifdef MP-WEIXIN
                            Payment.wechatMiniPay(result,this.payCallback,this.payFail)
                            // #endif

                            //微信App
                            // #ifdef APP-PLUS
                            Payment.wechatAppPay(result,this.payCallback,this.payFail)
                            // #endif
                        } else {
                            // #ifdef H5
                            //调起支付宝支付
                            Payment.aliPayH5(result,this.payCallback,this.payFail)
                            // #endif

                            // #ifdef APP-PLUS
                            Payment.aliPayApp(result,this.payCallback,this.payFail)
                            // #endif
                        }
                    })
                })
            },
            //小程序 openid
            loadMiniOpenId(){
                if(this.openid == ''){
                    API_Openid.fetchWeixinMiniOpenId().then(openid=>{
                        this.openid = openid
                    }).catch(e=>{
                        this.$u.toast(`获取openid出现意外错误`)
                    })
                }
            },
            //H5 openid
            loadH5OpenId(code){
                //非微信内部，跳过获取openid
                if (!this.is_weixin()){
                    this.openid = "h5openid"
                }
                if(this.openid == ''){
                    if(code == ''){
                        API_Openid.createRedirectUri().then(url=>{
                            location.href = url
                        })
                    }else{
                        API_Openid.fetchWeiXinH5OpenId(code).then(openid=>{
                            this.openid= openid
                        })
                    }
                }
            },
            payCallback() {
                uni.showModal({
                    title: '支付提示',
                    content: '请确认支付是否完成',
                    confirmText: '支付成功',
                    cancelText: '重新支付',
                    success: () => {
                        this.rechargeNumber = ''
                        this.getDepositBalance()
                    }
                })
            },
            payFail(err){
                console.log('fail:', err)
            },
            //获取预存款余额
            getDepositBalance() {
                API_Deposit.getDepositBalance().then(response => {
                    this.account_balance = response
                })
            },
            //获取支付方式
            getPaymentList() {
                API_Trade.getPaymentList('WAP').then(response => {
                    // 默认不选中支付方式
                    response.forEach(item => { item.selected = false })
                    this.paymentList = response
                    // 如果是在微信浏览器内则隐藏支付宝支付
                    // #ifdef H5
                    if(this.is_weixin()) {
                        this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
                    }
                    // #endif
                    // 如果是在小程序内则隐藏支付宝支付
                    // #ifdef MP
                    this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
                    // #endif
                })
            },
            //自定义返回按钮
            handleClose(){
                console.log('自定义返回')
                // #ifdef H5
                const pages = getCurrentPages()
                	if (pages.length > 1) {
                	uni.navigateBack(1)
                	return
                }
                //使用vue-router返回上一级
                let a = this.$router.go(-1)
                if (a == undefined) {
                	//重新定向跳转页面
                	uni.switchTab({
                	    url: '/pages/tabs/mine/mine'
                	});
                }
                return
                // #endif
                uni.navigateBack(1)
            }
        }
	}
</script>

<style lang="scss">
    .account-container {
        .account-balance-box {
            background: #FFFFFF;
            margin-bottom: 30rpx;
            .account-balance {
                font-size: 48rpx;
                line-height: 250%;
                text-align: center;
                font-weight: 600;
                color: #666666;
            }
            .account-balance-tip {
                text-align: center;
                padding-bottom: 80rpx;
                color: #999999;
                font-size: 26rpx;
            }
        }
        .account-from {
            background: #FFFFFF;
            margin: 20rpx;
            border-radius: 20rpx;
        }
        .account-recharge {
            .account-recharge-title {
                padding: 40rpx 32rpx 0;
                color: #333333;
                font-size: 28rpx;
            }

            .account-recharge-box {
                padding: 0 30rpx;
                display: flex;
                align-items: center;
                height: 120rpx;

                .account-recharge-lable {
                    width: 160rpx;
                    font-size: 28rpx;
                    color: #333333;
                    text-align: right;
                }

                .input-group {
                    display: inline-table;
                    width: 400rpx;
                    border-collapse: separate;
                    position: relative;
                    font-size: 28rpx;
                    .input-inner {
                        display: table-cell;
                        color: #606266;
                        border-radius: 8rpx;
                        border: 2rpx solid #dcdfe6;
                        box-sizing: border-box;
                        height: 80rpx;
                        line-height: 1;
                        padding: 0 30rpx;
                        transition: border-color .2s cubic-bezier(.645,.045,.355,1);
                        width: 100%;
                        vertical-align: middle;
                        font-size: 28rpx;
                        border-top-right-radius: 0;
                        border-bottom-right-radius: 0;
                        &:focus {
                            border-color: #409eff;
                        }
                    }
                    .input-append {
                        display: table-cell;
                        position: relative;
                        background-color: #f5f7fa;
                        color: #909399;
                        vertical-align: middle;
                        border: 2rpx solid #dcdfe6;
                        border-radius: 8rpx;
                        padding: 0 40rpx;
                        width: rpx;
                        white-space: nowrap;
                        border-left: 0;
                        border-top-left-radius: 0;
                        border-bottom-left-radius: 0;
                    }
                }
            }
        }

        .payment-view {
            margin: 20rpx;
            border-radius: 20rpx;
            background-color: #FFFFFF;
            .cell-view {
                border-top: 2rpx solid #E5E5E5;
            }
            .cell-icon {
                padding: 10rpx 0rpx;
            }
            .cell-title {
                text-align: right;
                flex: 1;
                margin: 0 20rpx;
                font-size: 30rpx;
                font-weight: bold;
            }
        }
    }
    /deep/ {
        .custom-icon-xuanze {
            color: #ff5000;
            font-size: 40rpx !important;
        }
        .custom-icon-choose {
            font-size: 40rpx !important;
        }
    }
</style>
